package game.kcp;


import game.handler.IMessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.netty.buffer.ByteBuf;

import java.util.HashMap;
import java.util.Map;

public class KcpMesssageServerHandler implements KcpListerner{
	private static final Logger logger = LoggerFactory.getLogger(KcpMesssageServerHandler.class);
	public Map<Integer, IMessageHandler> handlerMap = new HashMap<>();

	@Override
	public void handleReceive(ByteBuf buf, KcpOnUdp kcp) {
		try {
			while (buf.readableBytes() >= 4) {
				buf.markReaderIndex();
				int curFrameLen = buf.readIntLE();
				// 数据内容还不足
				if (buf.readableBytes() < curFrameLen) {
					// 重置rederIndex
					buf.resetReaderIndex();
					return;
				}
				int msgId = buf.readIntLE();
				byte[] dataBytes = new byte[curFrameLen - 4];
				buf.readBytes(dataBytes);
				logger.info("收到消息id:{}", msgId);
				if (handlerMap.containsKey(msgId)) {
					handlerMap.get(msgId).handKcpMsg(kcp, dataBytes);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			if (buf.refCnt() > 0) {
				buf.release(buf.refCnt());
			}
		}
	}

	@Override
	public void handleException(Throwable ex, KcpOnUdp kcp) {

	}

	@Override
	public void handleClose(KcpOnUdp kcp) {
		System.out.println("断开与客户端的连接!!");
	}

	@Override
	public void handleInit() {

	}
}
